package org.eclipse.stp.policy_builder.model.source;

import java.util.ArrayList;

import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.IExtension;
import org.eclipse.stp.policy_builder.model.exceptions.DescriptorException;
import org.eclipse.stp.policy_builder.util.AbstractExtensionParser;
import org.eclipse.stp.policy_builder.util.PolicyBuilderLog;

public class SourceExtensionParser<Target extends SourceType> extends AbstractExtensionParser implements ISourceTagProvider{
    
    
    
    private final ArrayList<Target> cachedTypes = new ArrayList<Target>();
    
	public SourceExtensionParser(String pluginID,String extPoint){
		setPluginID(pluginID);
		setExtPoint(extPoint);
	}
	@Override
	public Target parseElement(IConfigurationElement element, Object[] args)throws DescriptorException {
		if(TAG_SOURCE.equals(element.getName())){
			SourceType proxy = new SourceType(element);
			IConfigurationElement[] children = element.getChildren();
			ParameterMap map = proxy.getParameterContainer();
			for(IConfigurationElement child : children){
				if(TAG_PARAM.equals(child.getName())){
					String name = child.getAttribute(PARAM_NAME);
					String type = child.getAttribute(PARAM_TYPE);
					String def = child.getAttribute(PARAM_DEFAULT);
					if(type==null)
						type = DEFAULT_TYPE_VALUE;
					SourceParameter temp = new SourceParameter(name,def,type);
					if(name!=null && type!=null){
						//map.setKey(name);
						map.setValue(name, temp);
					}
					else{
						throw new DescriptorException("Parameter [name] not Declared correctly or not present for source :"+element.getAttribute(SourceType.ATT_NAME));
					}
				}
			}
			return (Target) proxy;
		}
		
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public ArrayList<Target> run() {
		// TODO Auto-generated method stub
		IExtension[] extensions = getExtensions(pluginID, extPoint);
		for(IExtension ext : extensions){
			IConfigurationElement[] elements = ext.getConfigurationElements();
			for(IConfigurationElement elem : elements){
				Target proxyType;
				try {
					proxyType = parseElement(elem, null);
					if(proxyType!=null){ 
						cachedTypes.add(proxyType);
					}
				} catch (DescriptorException e) {
					// TODO Auto-generated catch block
					PolicyBuilderLog.logError(e);
				}
				
			}
		}
		return cachedTypes ;
	}
	
	
	
	
}
